Here’s a comparison of cookie, local storage, and session storage in terms of their purpose, size limits, lifespan, and example usage:
Storage Type | Purpose | Size Limit | Lifespan | Accessibility | Example Usage |
---|---|---|---|---|---|
Cookie | Store small amounts of data that can be sent to the server with each request | ~4KB per cookie | Can be set to expire or persist until manually deleted | Accessible to both client and server | Store user authentication token or user preferences |
Local Storage | Store larger amounts of data for long-term use | ~5–10MB (varies by browser) | Persistent until manually deleted | Accessible only on the client side | Store theme settings or user preferences |
Session Storage | Store temporary data for a single session | ~5MB | Cleared when the browser tab is closed | Accessible only on the client side | Store form data or temporary session info |
Read a cookie:
Get data from local storage:
Get data from session storage: